/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    BlobInputList, CCell, Table, TableBody, TableHead, TableRow, Text,
} from "customize-easy-ui-component";
import {
    CCellUnit, InspectRecordLayout, InternalItemProps, RepLink, SelectInput, useItemInputControl
} from "../../common/base";
import {useOmnipotentPrefMove, useOmnipotentPrefTitle} from "../../hook/useOmnipotentPref";
import {useMeasureInpFilter} from "../../common/hooks";
import {css} from "@emotion/react";
import {floatInterception, objNestSet} from "../../../common/tool";
import {concluF3Tran, 检查结论选} from "../../tools";

/**@param orc 报告存储
 * @param op 是给编辑器（以及原始记录）用的 ; 这没用到
 * */
const setConfigP =(orc:any,op:boolean)=> [
    ['查结构型', [{t:'3',s:1},{t:'C2.1结构型式检查',s:1},{cs:-1}], '车辆的主参数、主要结构型式与技术资料的描述应一致。',
          undefined,['车辆的主参数、主要结构型式与技术资料的描述一致。'] ],
    ['定重起量', [{t:'4',s:8},{t:'C2.2主要参数测定',s:8},{t:'额定起重量'}],
        `额定起重量( ${orc?.额起重??'—'} )kg。`, 'kg'],
    ['无货叉', [{},{},{t:'全长',s:2}],
        `无货叉：设计值( ${orc?.全长无叉??'—'} )mm,允差±1%。`, 'mm'],
    ['有货叉', [{}],
        `有货叉：设计值( ${orc?.全长有叉??'—'} )mm,允差±1%。`, 'mm'],
    ['轮全宽', [{},{},{t:'全宽',s:2}],
        `车轮宽：设计值（ ${orc?.车轮宽??'—'} )mm。额定起重量≤10000kg，允差±2%；额定起重量＞10000kg，允差±1.5%。`, 'mm'],
    ['架全宽', [{}],
        `车架宽：设计值（ ${orc?.车架宽??'—'} )mm。额定起重量≤10000kg，允差±1%；额定起重量＞10000kg，允差±1.5%。`, 'mm'],
    ['门架全高', [{},{},{t:'全高',s:3}],
        `不起升门架高度:设计值( ${orc?.门架高??'—'} )mm。额定起重量≤10000kg，允差±1%；额定起重量＞10000kg，允差±1.5%。`, 'mm'],
    ['顶架全高', [{}],
        `护顶架(司机室)高度:设计值( ${orc?.顶架高??'—'} )mm。额定起重量≤10000kg，允差±1%；额定起重量＞10000kg，允差±1.5%。`, 'mm'],
    ['最大全高', [{}],
        `作业时最大高度:设计值( ${orc?.最大高??'—'} )mm, 允差±1%。`, 'mm'],
    //拆分行: 轴距
    ['测轴距', [{t:'4',s:6},{t:'C2.2主要参数测定',s:6},{t:'轴距'}],
        `设计值( ${orc?.轴距??'—'} )mm，允差±1%。`, 'mm'],
    ['测前悬', [{},{},{t:'前悬距'}],
        `设计值( ${orc?.前悬距??'—'} )mm，允差±3%。`, 'mm'],
    ['测前轮距', [{},{},{t:'前轮距'}],
        `设计值( ${orc?.前轮距??'—'} )mm，允差±2%。`, 'mm'],
    ['测后轮距', [{},{},{t:'后轮距'}],
        `设计值( ${orc?.后轮距??'—'} )mm，允差±2%。`, 'mm'],
                    //【特殊】 2行有4个字段的：
    ['测隙下', [{},{},{t:'最小离地间隙',s:2}],
        `门架下端(空载/满载),≥设计值( ${orc?.地隙下空??'—'} ／ ${orc?.地隙下满??'—'} )mm 95%；`, 'mm'],
    ['测隙中', [{}],
        `车架中部(空载/满载),≥设计值( ${orc?.地隙中空??'—'} ／ ${orc?.地隙中满??'—'} )mm 95%；`, 'mm'],
    //拆分行: 布局宽度的调整需要;
    ['测最升', [{t:'4',s:5},{t:'C2.2主要参数测定',s:5},{t:'无载最大起升高度'}],
        `设计值( ${orc?.最起升??'—'} )mm,允差+1.5%。`, 'mm'],
    ['测自升', [{},{},{t:'自由起升高度'}],
        `设计值( ${orc?.自由升??'—'} )mm,允差±5%。`, 'mm'],
    ['测全自', [{},{},{t:'全自由起升高度'}],
        `设计值( ${orc?.全自升??'—'} )mm,允差±2%。`, 'mm'],
    ['测架前角', [{},{},{t:'门架（货叉）前倾角'}],
        `设计值( ${orc?.架前倾角??'—'} )°,允差±0.5°。`, '°'],
    ['测架后角', [{},{},{t:'门架（货叉）后倾角'}],
        `设计值( ${orc?.架后倾角??'—'} )°,允差±1°。`, '°'],
];

const itemsChk =setConfigP(undefined,true);
export const itemA结构型: string[] = ['测隙下2','测隙中2' ];             //【特殊】 2行有4个字段的：
itemsChk.forEach(([name, title, initIsp], i: number) => {
    itemA结构型.push(name as string);
});
const itemAm=itemA结构型.concat(['额起重','全长无叉','全长有叉','车轮宽','车架宽','门架高','顶架高','最大高','轴距','前悬距','前轮距','后轮距',
             '地隙下空','地隙下满','地隙中空','地隙中满','最起升','自由升','全自升','架前倾角','架后倾角']);

/**不同于普通机电的"印象派"做法： 结论栏目不是自动生成的，也是要人工选定！
 * 这两个行i==13,14 特殊，【配置 代码耦合】
 * */
export const StructuralType =
    React.forwardRef((
        {children, show, alone = true, refWidth, label, }: InternalItemProps, ref
    ) => {
      const {inp, setInp} = useItemInputControl({ref});
      const [getInpFilter] = useMeasureInpFilter(null, itemAm,);
      const config = setConfigP(inp,true);
      const titNode=useOmnipotentPrefTitle({config, });
      return (
          <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                               alone={alone} label={label!}>
            <Text variant="h5">{label}：</Text>
            {config.map(([name, _1, _2, unit,dfs]: any, i: number) => {
                const ispc=13===i || 14===i;        //特例的2行 多2个录入
              return (<React.Fragment key={i}>
                  <div css={{display: 'flex', flexWrap: 'wrap', alignItems: 'center'}}>
                      {titNode[i]}&nbsp;
                      <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap',width: '100%',maxWidth: 'fit-content'}}>
                       {i>0? '测量（界定）值' : '检查结果'}{ispc&&'，空载'}&nbsp; <BlobInputList value={inp?.[name]?.r || ''} rows={1}
                                         datalist={dfs?.[0] ? [dfs?.[0], '无此项。'] : undefined}
                                         style={{display: 'inline-flex', width: inp?.[name]?.r?.length>15? '28rem': i>0? '6rem':'14rem', maxWidth: '100%', fontSize: '1rem',}}
                                         listStyle={css({fontSize: '1rem',})}
                                         onListChange={v => objNestSet(name, 'r', v || undefined, inp, setInp)}/>{unit}
                       {i>0 && <>；</>}
                      </div>
                      {i>0 && <>结果={floatInterception(inp?.[name]?.r,i>17?1:0)??'—'} {unit}</>}
                      {ispc && <>
                          <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                              {'，满载'}&nbsp; <BlobInputList value={inp?.[name+'2'] || ''} rows={1}
                                         style={{display: 'inline-flex', width: '6rem', maxWidth: '100%', fontSize: '1rem',}}
                                         listStyle={css({fontSize: '1rem',})}
                                         onListChange={v => setInp({...inp, [name+'2']: v || undefined}) }/>{unit}；
                          </div>
                          结果={floatInterception(inp?.[name+'2'],0)??'—'} {unit}
                        </>
                      }
                      <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                          &nbsp;检查结论<SelectInput value={inp?.[name]?.c || ''} list={检查结论选} nMinW
                               style={{display: 'inline-flex', width: '5rem'}}
                               onChange={e => objNestSet(name, 'c', e.currentTarget.value || undefined, inp, setInp)}/>
                      </div>
                      <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                        备注<BlobInputList value={inp?.[name]?.m || ''} rows={1}
                                         style={{display: 'inline-flex', width: '12rem', maxWidth: '100%', fontSize: '1rem',}}
                                         listStyle={css({fontSize: '1rem',})}
                                         onListChange={v => objNestSet(name, 'm', v || undefined, inp, setInp)}/>
                      </div>
                  </div>
              </React.Fragment>);
            })}
            {children}
          </InspectRecordLayout>
      );
});
/**高阶函数   进一步去修饰 itemRender
 *@param op  是原始记录的页面。
 * 定制: @底下的config[i]?.[4][0]获取默认的结果栏目配置！
 * 注意配置耦合：两个行i==13,14 特殊，
* */
const guidancer=(op?:boolean)=>{
    //但：第一个行特例的： 纯文字，独一栏目。
    return (orc: any, name: string, i: number, item: any, xmcspan: number, unit: any,config:any[][]) =>{
        const ispc=13===i || 14===i;        //特例的2行 多2个录入
        return <>
            <CCell colSpan={xmcspan}>{item}</CCell>
            {0===i? <CCell colSpan={op?2:1}>{orc?.[name]?.r ?? '—'}</CCell>
                :
                ispc? <>
                        {op && <CCellUnit unit={unit}>{orc?.[name]?.r ?? '—'}／{orc?.[name+'2'] ?? '—'}</CCellUnit>}
                        <CCellUnit unit={unit}>{floatInterception(orc?.[name]?.r,0)??'—'}／{floatInterception(orc?.[name+'2'],0)??'—'}</CCellUnit>
                    </>
                    :
                    <>
                        {op && <CCellUnit unit={unit}>{orc?.[name]?.r ?? '—'}</CCellUnit>}
                        <CCellUnit unit={unit}>{floatInterception(orc?.[name]?.r,i>17?1:0)??'—'}</CCellUnit>
                    </>
            }
            {op? <CCell>{orc?.[name]?.c ?? '—'}</CCell>
                :
                <CCell>{concluF3Tran(orc?.[name]?.c)}</CCell>
            }
            <CCell>{orc?.[name]?.m}</CCell>
        </>;
    }
};
/**类似于机电类常见的项目列表， 但是拆分成几个独立部分组装的： 这里是其中一个组装的区域。
 * 8、样机检查   C2.1结构型式检查
 * 【特殊】正式报告版本 比原始记录版本少一个栏目！
 * 下面小部分是 独立table表格布局的，避免列宽度太紧凑了！
 * */
export const StructuralTypeVw = ({orc, rep, op, title}: { orc: any, rep: any, op?: boolean, title: any }
) => {
    const config =setConfigP(orc, op!);
    const fixed=op? ["3%","7%","7%","%", "13%", "12%", "5%", "9%"] : ["3.2%","6.8%","8%","%", "19%", "6%", "8.6%"];
    const fixedD=op? ["3%","7%","19%","%", "13%", "12%", "5%", "9%"] : ["3.2%","6.8%","19%","%", "19%", "6%", "8.6%"];
    const tbhead=<><TableRow>
            <CCell rowSpan={op?2:1}><Text css={{fontSize: '0.75rem'}}>序号</Text></CCell><CCell rowSpan={op?2:1}><Text css={{fontSize: '0.75rem'}}>检查项目</Text></CCell>
            <CCell colSpan={2} rowSpan={op?2:1}>内容及要求</CCell><CCell colSpan={op?2:1}>检查结果</CCell>
            <CCell rowSpan={op?2:1}><Text css={{fontSize: '0.75rem'}}>检查结论</Text></CCell><CCell rowSpan={op?2:1}>备注</CCell>
        </TableRow>
     {op && <TableRow><CCell><Text css={{fontSize: '0.75rem'}}>测量(界定)值</Text></CCell><CCell>结果</CCell></TableRow>}
    </>
    //序号不是递增生成的， 而是人工配置方式的标题！
    const [upper,downer] = useOmnipotentPrefMove({orc,
              config, split:[14],tag:'Struct',itemRender:guidancer(op), pcols: 3, noNo: true, unitCel: false});
   return <>
      <div css={{"@media print": {paddingBottom: '8rem', pageBreakInside: 'avoid'}}}>
          <Text id='StructuralType' variant="h4" css={{
              textAlign: op ? undefined : 'center', marginTop: '1rem',
          }}>{title}</Text>
          <div css={{display: 'flex', justifyContent: 'space-between'}}>
              <Text></Text>
              <Text>{op ? '记录' : '报告'}编号：{rep.isp.no}</Text>
          </div>
      </div>
      <Table fixed={fixed} css={{borderCollapse: 'collapse', "@media print": {marginTop: '-8rem'}}} tight miniw={800}>
          <TableHead>{tbhead}</TableHead>
          <TableBody>
              <RepLink rep={rep} tag={'StructuralType'}>
                  {upper}
              </RepLink>
          </TableBody>
      </Table>
      <div css={{"@media print": {paddingBottom: '4.7rem', pageBreakInside: 'avoid'}}}/>
      <Table fixed={fixedD} css={{borderCollapse: 'collapse', "@media print": {marginTop: '-4.7rem'}}} tight miniw={800}>
          <TableHead>{tbhead}</TableHead>
          <TableBody>
              <RepLink rep={rep} tag={'StructuralType'}>
                  {downer}
              </RepLink>
          </TableBody>
      </Table>
  </>;
};
